﻿<%@ Page Title="" Language="C#" MasterPageFile="~/Internal/Internal.Master" AutoEventWireup="true"
    CodeBehind="StaffManagement.aspx.cs" Inherits="Landscape.WebApp.Internal.Admin.StaffManagement"
    Theme="Internal" %>

<%@ Register Assembly="Telerik.Web.UI" Namespace="Telerik.Web.UI" TagPrefix="telerik" %>
<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="server">
    <script type="text/javascript" src="../../Scripts/ModuleMethods/LandscapeAdminActions.js"></script>
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">
    <asp:HiddenField ID="hfUserID" runat="server" />
    <asp:HiddenField ID="hfIsSysAdmin" runat="server" />
    <telerik:RadToolBar ID="rtbModuleActions" runat="server" Width="100%" OnClientButtonClicked="rtbModuleActions_OnClientButtonClicked"
        EnableShadows="True">
        <Items>
            <telerik:RadToolBarButton runat="server" CommandName="LIST" ImageUrl="~/Images/Search.png"
                Text="Search" CheckOnClick="True" ImagePosition="AboveText" Value="SEARCH">
            </telerik:RadToolBarButton>
            <telerik:RadToolBarButton runat="server" CommandName="NEW" ImageUrl="~/Images/Write.png"
                Text="New" CheckOnClick="True" ImagePosition="AboveText"  Value="NEW">
            </telerik:RadToolBarButton>
            <telerik:RadToolBarButton runat="server" CommandName="SAVE" ImageUrl="~/Images/Floppy.png"
                Text="Save" CheckOnClick="True" ImagePosition="AboveText" Value="SAVE">
            </telerik:RadToolBarButton>
            <telerik:RadToolBarButton runat="server" CommandName="DELETE" ImageUrl="~/Images/Delete_32x32.png"
                Text="Delete" CheckOnClick="True" ImagePosition="AboveText" Value="DELETE">
            </telerik:RadToolBarButton>
        </Items>
    </telerik:RadToolBar>
    <telerik:RadTabStrip ID="rtsUserManagement" runat="server" MultiPageID="RadMultiPage1"
        SelectedIndex="0" Width="100%">
        <Tabs>
            <telerik:RadTab runat="server" Text="Search Results" PageViewID="RadPageView1">
            </telerik:RadTab>
            <telerik:RadTab runat="server" Text="User Details" PageViewID="RadPageView2">
            </telerik:RadTab>
            <telerik:RadTab runat="server" Text="User Resources" PageViewID="RadPageView3" Selected="True">
            </telerik:RadTab>
        </Tabs>
    </telerik:RadTabStrip>
    <telerik:RadMultiPage ID="RadMultiPage1" runat="server" SelectedIndex="0" Width="100%">
        <telerik:RadPageView ID="RadPageView1" runat="server">
            <telerik:RadGrid ID="rgUsers" runat="server" AllowPaging="True" AutoGenerateColumns="False"
                CellSpacing="0" GridLines="None">
                <ClientSettings>
                    <Selecting AllowRowSelect="True" CellSelectionMode="None" />
                    <ClientEvents OnRowDataBound="rgUsers_OnRowDataBound" OnCommand="rgUsers_OnCommand"
                        OnGridCreated="rgUsers_OnGridCreated" />
                </ClientSettings>
                <MasterTableView>
                    <CommandItemSettings ExportToPdfText="Export to PDF" />
                    <RowIndicatorColumn FilterControlAltText="Filter RowIndicator column" Visible="True">
                        <HeaderStyle Width="20px" />
                    </RowIndicatorColumn>
                    <ExpandCollapseColumn FilterControlAltText="Filter ExpandColumn column" Visible="True">
                        <HeaderStyle Width="20px" />
                    </ExpandCollapseColumn>
                    <Columns>
                        <telerik:GridClientSelectColumn FilterControlAltText="Filter column column" UniqueName="column">
                        </telerik:GridClientSelectColumn>
                        <telerik:GridTemplateColumn DataField="Identity.LoginName" FilterControlAltText="Filter TemplateColumn column"
                            HeaderText="Login Name" UniqueName="TemplateColumn">
                            <ItemTemplate>
                                <asp:LinkButton ID="lbtn" runat="server"></asp:LinkButton>
                            </ItemTemplate>
                        </telerik:GridTemplateColumn>
                        <telerik:GridBoundColumn DataField="StaffCode" FilterControlAltText="Filter column1 column"
                            HeaderText="Staff Code" UniqueName="column1">
                        </telerik:GridBoundColumn>
                        <telerik:GridBoundColumn DataField="FirstName" FilterControlAltText="Filter column2 column"
                            HeaderText="First Name" UniqueName="column2">
                        </telerik:GridBoundColumn>
                        <telerik:GridBoundColumn DataField="LastName" FilterControlAltText="Filter column3 column"
                            HeaderText="Last Name" UniqueName="column3">
                        </telerik:GridBoundColumn>
                        <telerik:GridBoundColumn DataField="IsDisabled" FilterControlAltText="Filter column4 column"
                            HeaderText="Is Disabled" UniqueName="column4">
                        </telerik:GridBoundColumn>
                        <telerik:GridBoundColumn DataField="UpdatedBy" FilterControlAltText="Filter column5 column"
                            HeaderText="Updated By" UniqueName="column5">
                        </telerik:GridBoundColumn>
                        <telerik:GridBoundColumn DataField="UpdatedDate" FilterControlAltText="Filter column6 column"
                            HeaderText="Updated Date" UniqueName="column6">
                        </telerik:GridBoundColumn>
                    </Columns>
                    <EditFormSettings>
                        <EditColumn FilterControlAltText="Filter EditCommandColumn column">
                        </EditColumn>
                    </EditFormSettings>
                </MasterTableView>
                <FilterMenu EnableImageSprites="False">
                </FilterMenu>
            </telerik:RadGrid>
        </telerik:RadPageView>
        <telerik:RadPageView ID="RadPageView2" runat="server">
            <div class="ContentTabBody">
                <table style="width: 100%; height: 100%; vertical-align: top">
                    <tr>
                        <td width="170px">
                            <asp:Label ID="Label1" runat="server" Text="Is AD User :" SkinID="ContentLabel"></asp:Label>
                        </td>
                        <td width="400px">
                            <asp:CheckBox ID="cbIsADUser" runat="server" onclick="cbIsADUser_onClick(this);" />
                        </td>
                        <td>
                            &nbsp;
                        </td>
                    </tr>
                    <tr>
                        <td width="170px">
                            <asp:Label ID="Label2" runat="server" Text="Login User Name :" SkinID="ContentLabel"></asp:Label>
                        </td>
                        <td width="400px">
                            <telerik:RadTextBox ID="rtbxLoginName" runat="server">
                                <ClientEvents OnValueChanged="rtbxLoginName_OnValueChanged" />
                            </telerik:RadTextBox>
                        </td>
                        <td>
                            &nbsp;
                        </td>
                    </tr>
                    <tr>
                        <td width="170px">
                            <asp:Label ID="Label9" runat="server" Text="Staff Code :" SkinID="ContentLabel"></asp:Label>
                        </td>
                        <td width="400px">
                            <telerik:RadNumericTextBox ID="rntbxStaffCode" runat="server">
                            </telerik:RadNumericTextBox>
                        </td>
                        <td>
                            &nbsp;
                        </td>
                    </tr>
                    <tr>
                        <td width="170px">
                            <asp:Label ID="Label10" runat="server" Text="Location :" SkinID="ContentLabel"></asp:Label>
                        </td>
                        <td width="400px">
                            <telerik:RadComboBox ID="rcbLocation" runat="server">
                                <Items>
                                    <telerik:RadComboBoxItem runat="server" Text="--Select--" Value="0" />
                                    <telerik:RadComboBoxItem runat="server" Text="OFFICE" Value="OFFICE" />
                                    <telerik:RadComboBoxItem runat="server" Text="Vessel" Value="VESSEL" />
                                </Items>
                            </telerik:RadComboBox>
                        </td>
                        <td>
                            &nbsp;
                        </td>
                    </tr>
                    <tr>
                        <td width="170px">
                            <asp:Label ID="Label3" runat="server" Text="Salutation :" SkinID="ContentLabel"></asp:Label>
                        </td>
                        <td width="400px">
                            <telerik:RadComboBox ID="rcbSalutation" runat="server">
                                <Items>
                                    <telerik:RadComboBoxItem runat="server" Text="--Select--" Value="0" />
                                    <telerik:RadComboBoxItem runat="server" Text="Mr." Value="Mr." />
                                    <telerik:RadComboBoxItem runat="server" Text="Miss." Value="Miss." />
                                    <telerik:RadComboBoxItem runat="server" Text="Mrs." Value="Mrs." />
                                    <telerik:RadComboBoxItem runat="server" Text="Dr." Value="Dr." />
                                </Items>
                            </telerik:RadComboBox>
                        </td>
                        <td>
                            &nbsp;
                        </td>
                    </tr>
                    <tr>
                        <td width="170px">
                            <asp:Label ID="Label4" runat="server" Text="First Name :" SkinID="ContentLabel"></asp:Label>
                        </td>
                        <td width="400px">
                            <telerik:RadTextBox ID="rtbxFirstName" runat="server">
                            </telerik:RadTextBox>
                        </td>
                        <td>
                            &nbsp;
                        </td>
                    </tr>
                    <tr>
                        <td width="170px">
                            <asp:Label ID="Label5" runat="server" Text="Last Name :" SkinID="ContentLabel"></asp:Label>
                        </td>
                        <td width="400px">
                            <telerik:RadTextBox ID="rtbxLastName" runat="server">
                            </telerik:RadTextBox>
                        </td>
                        <td>
                            &nbsp;
                        </td>
                    </tr>
                    <tr>
                        <td width="170px">
                            <asp:Label ID="Label7" runat="server" Text="Email :" SkinID="ContentLabel"></asp:Label>
                        </td>
                        <td width="400px">
                            <telerik:RadTextBox ID="rtbxEMail" runat="server">
                            </telerik:RadTextBox>
                        </td>
                        <td>
                            &nbsp;
                        </td>
                    </tr>
                    <tr>
                        <td width="170px">
                            <asp:Label ID="Label8" runat="server" Text="Telephone :" SkinID="ContentLabel"></asp:Label>
                        </td>
                        <td width="400px">
                            <telerik:RadTextBox ID="rtbxTelephone" runat="server">
                            </telerik:RadTextBox>
                        </td>
                        <td>
                            &nbsp;
                        </td>
                    </tr>
                </table>
            </div>
        </telerik:RadPageView>
        <telerik:RadPageView ID="RadPageView3" runat="server">
            <div class="ContentTabBody">
                <asp:HiddenField ID="hfAssignedRoles" runat="server" />
                <asp:HiddenField ID="hfGroupID" runat="server" />
                <table>
                    <tr>
                        <th>
                            1. Select a Role
                        </th>
                        <th>
                            2. Choose Departments
                        </th>
                        <th>
                            3. Choose Vessels
                        </th>
                    </tr>
                    <tr>
                        <td style="vertical-align: top">
                            <telerik:RadComboBox ID="rcbRoles" runat="server" OnClientLoad="rcbRoles_OnClientLoad">
                            </telerik:RadComboBox>
                        </td>
                        <td style="vertical-align: top">
                            <telerik:RadListBox ID="rlbDepartments" runat="server" CheckBoxes="true" OnClientLoad="rlbDepartments_OnClientLoad">
                            </telerik:RadListBox>
                        </td>
                        <td style="vertical-align: top">
                            <telerik:RadListBox ID="rlbVessels" runat="server" CheckBoxes="true" OnClientLoad="rlbVessel_OnClientLoad">
                            </telerik:RadListBox>
                        </td>
                    </tr>
                    <tr>
                        <td colspan="3">
                            <telerik:RadGrid ID="rguserResourcesRoles" runat="server" AllowPaging="True" AutoGenerateColumns="False"
                                AllowMultiRowSelection="True" CellSpacing="0" GridLines="None">
                                <ClientSettings>
                                    <Selecting AllowRowSelect="True" CellSelectionMode="None" />
                                    <ClientEvents OnGridCreated="rguserResourcesRoles_OnGridCreated" OnCommand="rguserResourcesRoles_OnCommand"
                                        OnRowDataBound="rguserResourcesRoles_OnRowDataBound" />
                                    <Selecting AllowRowSelect="True" />
                                </ClientSettings>
                                <MasterTableView>
                                    <CommandItemSettings ExportToPdfText="Export to PDF" />
                                    <CommandItemSettings ExportToPdfText="Export to PDF" />
                                    <RowIndicatorColumn FilterControlAltText="Filter RowIndicator column" Visible="True">
                                        <HeaderStyle Width="20px" />
                                    </RowIndicatorColumn>
                                    <ExpandCollapseColumn FilterControlAltText="Filter ExpandColumn column" Visible="True">
                                        <HeaderStyle Width="20px" />
                                    </ExpandCollapseColumn>
                                    <Columns>
                                        <telerik:GridClientSelectColumn FilterControlAltText="Filter column column" HeaderText="#"
                                            UniqueName="column">
                                        </telerik:GridClientSelectColumn>
                                        <telerik:GridBoundColumn DataField="GroupId" FilterControlAltText="Filter column1 column"
                                            HeaderText="Group ID" UniqueName="column4">
                                        </telerik:GridBoundColumn>
                                        <telerik:GridBoundColumn DataField="RoleName" FilterControlAltText="Filter column1 column"
                                            HeaderText="Role Name" UniqueName="column1">
                                        </telerik:GridBoundColumn>
                                        <telerik:GridBoundColumn DataField="DepartmentName" FilterControlAltText="Filter column2 column"
                                            HeaderText="Department" UniqueName="column2">
                                        </telerik:GridBoundColumn>
                                        <telerik:GridBoundColumn DataField="VesselName" FilterControlAltText="Filter column3 column"
                                            HeaderText="Vessel" UniqueName="column3">
                                        </telerik:GridBoundColumn>
                                    </Columns>
                                    <EditFormSettings>
                                        <EditColumn FilterControlAltText="Filter EditCommandColumn column">
                                        </EditColumn>
                                    </EditFormSettings>
                                </MasterTableView>
                                <FilterMenu EnableImageSprites="False">
                                </FilterMenu>
                            </telerik:RadGrid>
                        </td>
                    </tr>
                </table>
            </div>
        </telerik:RadPageView>
    </telerik:RadMultiPage>
    <script type="text/javascript">

        function cbIsADUser_onClick(v) {
            return true;
        }

        function rtbModuleActions_OnClientButtonClicked(sender, args) {
            processCommands(args.get_item().get_commandName());
            args.get_item().set_checked(false);
        }

        function switchTab(pTabIdx) {
            var rts = $find('<%=rtsUserManagement.ClientID %>');
            rts.get_tabs().getTab(pTabIdx).select();
        }

        function rlbVessel_OnClientLoad(sender) {
            Landscape.AdministrativeActions.GetUserVessels(MASTER_GetCurrentUserCode(), function (result, e) {

                for (var idx = 0; idx < result.length; idx++) {
                    var item = new Telerik.Web.UI.RadListBoxItem();
                    item.set_text(result[idx].Name);
                    item.set_value(result[idx].ID);

                    sender.get_items().add(item);
                }

            }, function (result, e) { N_NotifyMessage('Error !!!', result.get_message(), 2); });
        }

        function rcbVessel_OnClientLoad(sender, args) {
            Landscape.AdministrativeActions.GetVesselListByName('', -1, -1, function (result, e) {
                var cnt = result.length;
                var comboItemCollection = sender.get_items();

                var comboItem = new Telerik.Web.UI.RadComboBoxItem();
                comboItem.set_text('--Select--');
                comboItem.set_value('00000000-0000-0000-0000-000000000000');

                comboItemCollection.add(comboItem);

                if (cnt > 0) {
                    for (idx = 0; idx < cnt; idx++) {
                        comboItem = new Telerik.Web.UI.RadComboBoxItem();
                        comboItem.set_text(result[idx].Name);
                        comboItem.set_value(result[idx].ID);

                        comboItemCollection.add(comboItem);
                    }
                }

                comboItemCollection.getItem(0).select();

            }, function (result, e) { N_NotifyMessage('Error !!!', result.get_message(), 2); });
        }

        function processCommands(pCmdName) {
            switch (pCmdName) {
                case 'SAVE':
                    {
                        if (GLOBAL_CheckUserHasPrivilege('CREATE') || GLOBAL_CheckUserHasPrivilege('EDIT')) {
                            performSave();
                        }
                        else {
                            N_NotifyMessage('Access Denied !!!', 'You don\'t have privileges to perform this operation. Please contact administrator ', 2);
                        }
                        break;
                    }

                case 'LIST':
                    {
                        if (GLOBAL_CheckUserHasPrivilege('SEARCH')) {
                            performList();
                        }
                        else {
                            N_NotifyMessage('Access Denied !!!', 'You don\'t have privileges to perform this operation. Please contact administrator ', 2);
                        }
                        break;
                    }

                case 'DELETE':
                    {
                        if (GLOBAL_CheckUserHasPrivilege('DELETE')) {
                            perfromDelete();
                        }
                        else {
                            N_NotifyMessage('Access Denied !!!', 'You don\'t have privileges to perform this operation. Please contact administrator ', 2);
                        }
                        break;
                    }

                case 'NEW':
                    {
                        if (GLOBAL_CheckUserHasPrivilege('EDIT')) {
                            performNew();
                            switchTab(1);
                        }
                        else {
                            N_NotifyMessage('Access Denied !!!', 'You don\'t have privileges to perform this operation. Please contact administrator ', 2);
                        }
                        break;
                    }
            }
        }

        function rtbxLoginName_OnValueChanged(sender, args) {
            if (args.get_newValue().trim() != '') {
                var userID = $get('<%=hfUserID.ClientID %>').value;
                if (userID.trim() != '' && args.get_oldValue().trim() != '') {
                    Landscape.AdministrativeActions.CheckForDuplicateLogin(args.get_newValue(), function (result, e) {
                        if (result) {
                            N_NotifyMessage('Duplicate Login Name !!!', 'There is a user already in the system with the same login name. Please choose a diffrent name.', 3);
                            args.set_cancel(true);
                            sender.set_value('');
                        }
                    }, function (result, e) { N_NotifyMessage('Error !!!', result.get_message(), 2); });
                }
            }
        }

        function GetActiveTabIndex() {
            var rts = $find('<%=rtsUserManagement.ClientID %>');
            if (rts != null) {
                return rts.get_selectedTab().get_index();
            }
            else {
                throw 'Cannot load RadTabStrip.';
            }
        }

        function performSave() {
            var loginName = $find('<%=rtbxLoginName.ClientID %>').get_value();
            var isAdUser = $get('<%=cbIsADUser.ClientID %>').checked;
            var salutation = $find('<%=rcbSalutation.ClientID %>').get_value();
            var firstName = $find('<%=rtbxFirstName.ClientID %>').get_value();
            var lastName = $find('<%=rtbxLastName.ClientID %>').get_value();
            var isTpUser = false;
            var email = $find('<%=rtbxEMail.ClientID %>').get_value();
            var telePhone = $find('<%=rtbxTelephone.ClientID %>').get_value();
            var staffCode = $find('<%=rntbxStaffCode.ClientID %>').get_value();
            var userID = $get('<%=hfUserID.ClientID %>').value;
            var selectedRoles = $get('<%=hfAssignedRoles.ClientID %>').value;
            var location = $find('<%=rcbLocation.ClientID %>').get_value();            

            if (validateUserInput()) {
                var userMaster = new Landscape.UserMaster();
                userMaster.ID = (userID.trim() == '' ? '00000000-0000-0000-0000-000000000000' : userID);
                userMaster.FirstName = firstName;
                userMaster.StaffCode = (staffCode == '' ? 0 : staffCode);
                userMaster.LastName = lastName;
                userMaster.Salutation = salutation;
                userMaster.IsTpUser = isTpUser;
                userMaster.EMail = email;
                userMaster.PhoneNumber = telePhone;
                userMaster.IsSystemAdmin = false;
                userMaster.IsDisabled = false;
                userMaster.IsDeleted = false;
                userMaster.CreatedBy = MASTER_GetCurrentUserCode();
                userMaster.UpdatedBy = MASTER_GetCurrentUserCode();
                userMaster.Location = location;

                userMaster.Identity = new Landscape.UserIdentity();

                userMaster.Identity.LoginName = loginName;
                userMaster.Identity.IsAdUser = isAdUser;

                Landscape.AdministrativeActions.SaveUser(userMaster,
                function (result, e) { N_NotifyMessage('Successfull !!!', 'User details saved successfully.', 1); },
                function (result, e) { N_NotifyMessage('Error !!!', result.get_message(), 2); });
            }

            //User Resources
            if (GetActiveTabIndex() == 2) {
                var rcbRoles = $find('<%=rcbRoles.ClientID %>');
                var rblDepartments = $find('<%=rlbDepartments.ClientID %>');
                var rblVessels = $find('<%=rlbVessels.ClientID %>');

                var roleID = rcbRoles.get_value();

                var departments = new Array();
                var selectedDepartments = rblDepartments.get_checkedItems();
                if (selectedDepartments.length > 0) {
                    for (idx = 0; idx < selectedDepartments.length; idx++) {
                        departments.push(selectedDepartments[idx].get_value());
                    }
                }

                var vessles = new Array();
                var selectedVessels = rblVessels.get_checkedItems();
                if (selectedVessels.length > 0) {
                    for (idx = 0; idx < selectedVessels.length; idx++) {
                        vessles.push(selectedVessels[idx].get_value());
                    }
                }

                Landscape.AdministrativeActions.UpdateUserResources(MASTER_GetCurrentBusinessObject().ID, roleID, vessles, departments, $get('<%=hfGroupID.ClientID %>').value, function (result, e) {
                    N_NotifyMessage('Successfull !!!', 'User roles and resources saved successfully.', 1);
                    loadCurrentUserRoles();
                    clearGroupData();
                }, function (result, e) { N_NotifyMessage('Error !!!', result.get_message(), 2); });
            }

        }

        function rlbDepartments_OnClientLoad(sender, args) {
            Landscape.AdministrativeActions.GetUserDepartments(MASTER_GetCurrentUserCode(), function (result, e) {
                for (var idx = 0; idx < result.length; idx++) {
                    var item = new Telerik.Web.UI.RadListBoxItem();
                    item.set_text(result[idx].Name);
                    item.set_value(result[idx].ID);

                    e.get_items().add(item);
                }

            }, function (result, e) { N_NotifyMessage('Error !!!', result.get_message(), 2); }, sender);
        }

        function perfromDelete() {
            var rts = $find('<%=rtsUserManagement.ClientID %>');
            if (rts.get_selectedTab().get_index() == 1) {
                //Details Tab
                if ($get('<%=hfUserID.ClientID %>').value.trim() != '') {
                    if (confirm('Do you really want to delete this user?')) {
                        Landscape.AdministrativeActions.DeleteUser($get('<%=hfUserID.ClientID %>').value.trim(), MASTER_GetCurrentUserCode(), function (result, e) {
                            N_NotifyMessage('Success !!!', 'The selected user deleted successfully.', 1);
                            performNew();
                        },
                    function (result, e) { N_NotifyMessage('Error !!!', result.get_message(), 2); });
                    }
                }
                else {
                    N_NotifyMessage('No Active User', 'Please select a user to delete.', 2);
                }
            }

            if (rts.get_selectedTab().get_index() == 0) {
                //Search Tab
                var radGrid = $find('<%=rgUsers.ClientID %>');
                if (radGrid.get_selectedItems().length > 0) {
                    if (confirm('Do you want to delete the selected user(s)?')) {
                        for (var idx = 0; idx < radGrid.get_selectedItems().length; idx++) {
                            var uID = radGrid.get_selectedItems()[idx].get_dataItem().ID;
                            Landscape.AdministrativeActions.DeleteUser(uID, MASTER_GetCurrentUserCode(), function (result, e) { }, function (result, e) {
                                N_NotifyMessage('Error !!!', result.get_message(), 2);
                            });
                        }
                        performNew();
                        performList();
                    }
                }
            }
        }

        function validateUserInput() {
            var loginName = $find('<%=rtbxLoginName.ClientID %>').get_value();
            var isAdUser = $get('<%=cbIsADUser.ClientID %>').checked;
            var salutation = $find('<%=rcbSalutation.ClientID %>').get_value();
            var firstName = $find('<%=rtbxFirstName.ClientID %>').get_value();
            var lastName = $find('<%=rtbxLastName.ClientID %>').get_value();
            var isTpUser = false;
            var email = $find('<%=rtbxEMail.ClientID %>').get_value();
            var telePhone = $find('<%=rtbxTelephone.ClientID %>').get_value();
            var staffCode = $find('<%=rntbxStaffCode.ClientID %>').get_value();
            var userID = $get('<%=hfUserID.ClientID %>').value;
            var selectedRoles = $get('<%=hfAssignedRoles.ClientID %>').value;            

            var regExp = new RegExp("^[a-zA-Z0-9_]{2,50}$");
            var regExp2 = new RegExp("^[a-zA-Z0-9_\"\$%&@\!/\\s,.:\(\)]{2,255}$");
            var regExp3 = new RegExp("^[a-zA-Z0-9_\\s]{2,50}$");
            var regExp4 = new RegExp("^[0-9\\s\[\]\+]{2,255}$");
            var regExp5 = new RegExp("^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$");

            var errorString = '<ul>';
            var hasError = false;

            /*if (!regExp.test(loginName)) {
            errorString += '<li>Login name should not have special charectors and must be between 2 to 50 charectors.</li>';
            hasError = true;
            }*/
            if (!regExp3.test(firstName)) {
                errorString += '<li>First name should not have special charectors and must be between 2 to 255 charectors.</li>';
                hasError = true;
            }
            if (!regExp5.test(email)) {
                errorString += '<li>EMail should have correct format and must be between 2 to 255 charectors.</li>';
                hasError = true;
            }           

            if (hasError) {
                N_NotifyMessage('Please check the following !!!', errorString + '</ul>', 2);
            }

            return !hasError;
        }

        function performList() {
            var radGrid = $find('<%=rgUsers.ClientID %>').get_masterTableView();

            Landscape.AdministrativeActions.GetUsersByPage(radGrid.get_currentPageIndex(), radGrid.get_pageSize(), onUserListRecieved, function (result, e) { N_NotifyMessage('Error !!!', result.get_message(), 2); });

            Landscape.AdministrativeActions.GetUsersCount(function (result, e) {
                radGrid.set_virtualItemCount(result);
            }, function (result, e) { N_NotifyMessage('Error !!!', result.get_message(), 2); });

            var tabStrip = $find('<%=rtsUserManagement.ClientID %>');
            tabStrip.findTabByText('Search Results').set_selected(true);
        }

        function onUserListRecieved(result, e) {
            var gridMasterTable = $find('<%=rgUsers.ClientID %>').get_masterTableView();
            gridMasterTable.set_dataSource(result);
            gridMasterTable.dataBind();
        }

        function rgUsers_OnGridCreated(sender, args) {
            var gridMasterTable = sender.get_masterTableView();
            gridMasterTable.set_dataSource(new Array());
            gridMasterTable.dataBind();
        }

        function rgUsers_OnCommand(sender, args) {
            switch (args.get_commandName()) {
                case 'PageSize':
                case 'Page':
                    {
                        performList();
                        break;
                    }
            }
            args.set_cancel(true);
        }

        function rgUsers_OnRowDataBound(sender, args) {
            var lblBtn = args.get_item().findElement("lbtn");
            if (lblBtn != null) {
                lblBtn.innerHTML = args.get_dataItem().Identity.LoginName;
                lblBtn.href = "javascript:loadUserData('" + args.get_dataItem()['ID'] + "')";
            }
            else {
                var cell1 = args.get_item().get_cell('TemplateColumn');
                var ctrl = "<a href='javascript:loadUserData({0})'>{1}</a>";
                cell1.innerHTML = String.format(ctrl, String.format("'{0}'", args.get_dataItem()['ID']), args.get_dataItem().Identity.LoginName);
            }
        }

        function loadUserData(userID) {
            Landscape.AdministrativeActions.GetUserByID(userID, function (result, e) {
                $find('<%=rtbxLoginName.ClientID %>').set_value(result.Identity.LoginName);
                $get('<%=cbIsADUser.ClientID %>').checked = result.Identity.IsAdUser;
                $find('<%=rcbSalutation.ClientID %>').findItemByValue(result.Salutation).select();
                $find('<%=rtbxFirstName.ClientID %>').set_value(result.FirstName);
                $find('<%=rtbxLastName.ClientID %>').set_value(result.LastName);
                $find('<%=rtbxEMail.ClientID %>').set_value(result.EMail);
                $find('<%=rtbxTelephone.ClientID %>').set_value(result.PhoneNumber);
                $find('<%=rntbxStaffCode.ClientID %>').set_value(result.StaffCode);
                $get('<%=hfUserID.ClientID %>').value = result.ID;
                $get('<%=hfIsSysAdmin.ClientID %>').value = result.IsSystemAdmin;
                $get('<%=hfAssignedRoles.ClientID %>').value = '';

                if (result.Roles != null && result.Roles.length > 0) {
                    for (var idx = 0; idx < result.Roles.length; idx++) {
                        $get('<%=hfAssignedRoles.ClientID %>').value += result.Roles[idx].ID + ',';
                    }
                }
                MASTER_StoreCurrentBusinessObject(result);
                loadCurrentUserRoles();
                switchTab(1);
            }, function (result, e) { N_NotifyMessage('Error !!!', result.get_message(), 2); });
        }

        function performNew() {
            $find('<%=rtbxLoginName.ClientID %>').set_value('');
            $get('<%=cbIsADUser.ClientID %>').checked = false;
            $find('<%=rcbSalutation.ClientID %>').findItemByValue('0').select();
            $find('<%=rtbxFirstName.ClientID %>').set_value('');
            $find('<%=rtbxLastName.ClientID %>').set_value('');
            $find('<%=rtbxEMail.ClientID %>').set_value('');
            $find('<%=rtbxTelephone.ClientID %>').set_value('');
            $find('<%=rntbxStaffCode.ClientID %>').set_value('');
            $get('<%=hfUserID.ClientID %>').value = '';
            $get('<%=hfIsSysAdmin.ClientID %>').value = false;
            $get('<%=hfAssignedRoles.ClientID %>').value = '';
            loadCurrentUserRoles();
        }

        //User Roles Related Functions
        //***********************************************************************

        function loadCurrentUserRoles() {
            //This creates a client side object for rad grid
            //Load the current loged in user's roles
            var sender = $find('<%=rguserResourcesRoles.ClientID %>');
            sender.clearSelectedItems();

            if (MASTER_GetCurrentBusinessObject() != null) {
                Landscape.AdministrativeActions.GetUserResources(MASTER_GetCurrentBusinessObject().ID, 0, 10, function (result, e) {
                    var gridMasterTable = e.get_masterTableView();
                    gridMasterTable.set_dataSource(result);
                    gridMasterTable.dataBind();
                }, function (result, e) { N_NotifyMessage('Error !!!', result.get_message(), 2); }, sender);

                Landscape.AdministrativeActions.GetUserResourceCount(MASTER_GetCurrentBusinessObject().ID, function (result, e) {
                    var radGrid = e.get_masterTableView();
                    radGrid.set_virtualItemCount(result);
                }, function (result, e) { N_NotifyMessage('Error !!!', result.get_message(), 2); }, sender);
            }
        }

        function rcbRoles_OnClientLoad(sender, args) {
            sender.clearSelection();

            Landscape.AdministrativeActions.GetUserRoles(MASTER_GetCurrentUserCode(), 0, 10, function (result, e) {
                var items = e.get_items();
                e.trackChanges();

                var selectItem = new Telerik.Web.UI.RadComboBoxItem();
                selectItem.set_text('-Select-');
                selectItem.set_value('00000000-0000-0000-0000-000000000000');

                items.add(selectItem);

                for (idx = 0; idx < result.length; idx++) {
                    var comboItem = new Telerik.Web.UI.RadComboBoxItem();
                    comboItem.set_text(result[idx].Name);
                    comboItem.set_value(result[idx].ID);

                    items.add(comboItem);
                }
                e.commitChanges();

            }, function (result, e) { N_NotifyMessage('Error !!!', result.get_message(), 2); }, sender);
        }

        function rguserResourcesRoles_OnRowDataBound(sender, args) {
            var cell1 = args.get_item().get_cell('Column4');
            var ctrl = "<a href='javascript:loadGroupData({0})'>{0}</a>";
            cell1.innerHTML = String.format(ctrl, args.get_dataItem()['GroupID']);
        }

        function clearGroupData() {
            $get('<%=hfGroupID.ClientID %>').value = '';
            var rcbRoles = $find('<%=rcbRoles.ClientID %>');
            rcbRoles.findItemByValue('00000000-0000-0000-0000-000000000000').select();
            var rlbDept = $find('<%=rlbDepartments.ClientID %>');
            while (rlbDept.get_checkedItems().length > 0) {
                rlbDept.get_checkedItems()[0].uncheck();
            }

            var rlbVsls = $find('<%=rlbVessels.ClientID %>');
            while (rlbVsls.get_checkedItems().length > 0) {
                rlbVsls.get_checkedItems()[0].uncheck();
            }
        }

        function loadGroupData(groupID) {
            Landscape.AdministrativeActions.GetUserResourcesByGroup(MASTER_GetCurrentBusinessObject().ID, groupID, function (result, e) {
                var rlbDept = $find('<%=rlbDepartments.ClientID %>');
                while (rlbDept.get_checkedItems().length > 0) {
                    rlbDept.get_checkedItems()[0].uncheck();
                }

                var rlbVsls = $find('<%=rlbVessels.ClientID %>');
                while (rlbVsls.get_checkedItems().length > 0) {
                    rlbVsls.get_checkedItems()[0].uncheck();
                }

                var rcbRoles = $find('<%=rcbRoles.ClientID %>');
                $get('<%=hfGroupID.ClientID %>').value = result[0].GroupID;

                for (idx = 0; idx < result.length; idx++) {
                    if (rlbDept.findItemByValue(result[idx].DepartmentID) != null)
                        rlbDept.findItemByValue(result[idx].DepartmentID).check();

                    if (rlbVsls.findItemByValue(result[idx].VesselID) != null)
                        rlbVsls.findItemByValue(result[idx].VesselID).check();

                    if (rcbRoles.findItemByValue(result[idx].RoleID) != null)
                        rcbRoles.findItemByValue(result[idx].RoleID).select();
                }
            }, function (result, e) { N_NotifyMessage('Error !!!', result.get_message(), 2); });
        }

        function rguserResourcesRoles_OnGridCreated(sender, args) {

            var gridMasterTable = sender.get_masterTableView();
            gridMasterTable.set_dataSource(new Array());
            gridMasterTable.dataBind();
        }

        function rguserResourcesRoles_OnCommand(sender, args) {
            switch (args.get_commandName()) {
                case 'PageSize':
                case 'Page':
                    {
                        loadCurrentUserRoles();
                        break;
                    }
            }
            args.set_cancel(true);
        }

        function rgSystemRoles_OnRowDataBound(sender, args) {
            var selectedRoles = $get('<%=hfAssignedRoles.ClientID %>').value;
            if (selectedRoles.indexOf(args.get_dataItem().ID) != -1)
                args.get_item().set_selected(true);
        }

        function rgSystemRoles_OnRowSelected(sender, args) {

            var rID = args.get_item().get_dataItem().ID;
            var selectedRoles = $get('<%=hfAssignedRoles.ClientID %>').value;
            var allRoles = selectedRoles.split(',');
            var assgned = false;
            for (idx = 0; idx < allRoles.length; idx++) {
                if (allRoles[idx] == rID)
                    assgned = true;
            }

            if (!assgned) {
                $get('<%=hfAssignedRoles.ClientID %>').value += rID + ',';
            }
        }

        function rgSystemRoles_OnRowDeselected(sender, args) {

            var rID = args.get_item().get_dataItem().ID;
            var selectedRoles = $get('<%=hfAssignedRoles.ClientID %>').value;
            var allRoles = selectedRoles.split(',');
            var newRoleSet = '';
            for (idx = 0; idx < allRoles.length; idx++) {
                if (allRoles[idx] != rID)
                    newRoleSet += allRoles[idx] + ',';
            }

            $get('<%=hfAssignedRoles.ClientID %>').value = newRoleSet;
        }       
    </script>
</asp:Content>
